#!/usr/bin/env python

import sys
from hashlib import sha1
#import struct 
#import socket
import os

DEFAULT_CHUNK_SIZE = 262144 # 256 kb

# Check command line arguments.
if len(sys.argv) < 2:
    print "Usage: ./munch.py [-c chunksize] [-b brook-file] file-to-seed tracker"
    sys.exit(1)

# Check if a chunk size is given.
chunk_size = DEFAULT_CHUNK_SIZE
if '-c' in sys.argv:
    try:
        chunk_size = int(sys.argv[sys.argv.index('-c') + 1])
    except Exception, e:
        print 'Error reading chunk size. Exception message = "%s"'%e.args[0]
        sys.exit(1)

# Check if a brook file name is given.
input_file = sys.argv[-2]
brook_file_name = os.path.basename(input_file) + '.brook'
if '-b' in sys.argv:
    try:
        brook_file_name = sys.argv[sys.argv.index('-b') + 1]
        if brook_file_name[-6:] != '.brook':
            brook_file_name += '.brook'
    except Exception, e:
        print 'Error reading brook file name. Exception message = "%s"'%e.args[0]
        sys.exit(1)

# Try to open the input file.
try:
    infile = open(input_file, 'rb')
except Exception, e:
    print "Error opening input file. Error code =", e.args[0]
    sys.exit(1)

# Store the tracker name. One _could_ add validation here...
tracker = sys.argv[-1]

# Start reading in the chunks.
brook_id = sha1()
chunks = []
chunk = infile.read(chunk_size)
last_chunk_size = 0
while chunk != "":
    brook_id.update(chunk)
    chunks.append(sha1(chunk).hexdigest())
    last_chunk_size = len(chunk)
    chunk = infile.read(chunk_size)
infile.close()

# Write the .brook file.
try:
    outfile = open(brook_file_name, 'w')
    print >> outfile, 'tracker = %s'%tracker
    print >> outfile, 'infile = %s'%input_file
    print >> outfile, 'brook_id = %s'%brook_id.hexdigest()
    print >> outfile, 'chunk_size = %s'%chunk_size
    print >> outfile, 'last_chunk_size = %s'%last_chunk_size
    cnt = 0
    for chunk in chunks:
        print >> outfile, 'chunk%i = %s'%(cnt, chunk)
        cnt += 1
except Exception, e:
    print 'Error writing .brook file. Exception message = "%s"'%e.args[0]
    sys.exit(1)
finally:
    try: outfile.close() 
    except: pass

